package com.atguigu.auth.service.impl;

import com.atguigu.auth.mapper.SysRoleMapper;
import com.atguigu.auth.service.SysRoleService;
import com.atguigu.auth.service.SysUserRoleService;
import com.atguigu.model.system.SysRole;
import com.atguigu.model.system.SysUserRole;
import com.atguigu.vo.system.AssginRoleVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author dale
 * @title SysRoleServiceImpl
 * @date 2023/5/30 21:25
 */
@Service
public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRole> implements SysRoleService {
    @Autowired
    private SysUserRoleService sysUserRoleService;

    //查询所有角色 和当前用户所属角色
    @Override
    public Map<String, Object> findRoleDataByUserId(Long userId) {
        //1.查询所有角色，返回list集合
        List<SysRole> allRoleList = baseMapper.selectList(null);

        //2.根据userid查询用户所属的角色id
        LambdaQueryWrapper<SysUserRole> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysUserRole::getUserId,userId);
        List<SysUserRole> existUserRoleList = sysUserRoleService.list(wrapper);
        //从查询处理的角色列表遍历得到其中的角色id
        ArrayList<Long> list = new ArrayList<>();
        for (SysUserRole sysUserRole:existUserRoleList) {
            Long roleId = sysUserRole.getRoleId();
            list.add(roleId);
        }

        //3.根据角色id去角色列表里找,找出所属角色
        List<SysRole> assginRoleList = new ArrayList<>();
        for (SysRole role : allRoleList) {
            //已分配
            if(list.contains(role.getId())) {
                assginRoleList.add(role);
            }
        }

        //4.将数据封装到map集合
        Map<String, Object> roleMap = new HashMap<>();
        roleMap.put("assginRoleList", assginRoleList);
        roleMap.put("allRoleList", allRoleList);
        return roleMap;
    }

    // 为用户分配角色
    @Override
    public void doAssign(AssginRoleVo assginRoleVo) {
        //将用户已分配的角色删除
        LambdaQueryWrapper<SysUserRole> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysUserRole::getUserId,assginRoleVo.getUserId());
        sysUserRoleService.remove(wrapper);

        //重新进行分配
        List<Long> roleIdList = assginRoleVo.getRoleIdList();
        for (Long roleId:roleIdList) {
            if (StringUtils.isEmpty(roleId)){
                continue;
            }
            SysUserRole sysUserRole = new SysUserRole();
            sysUserRole.setRoleId(roleId);
            sysUserRole.setUserId(assginRoleVo.getUserId());
            sysUserRoleService.save(sysUserRole);
        }
    }


}
